package com.zhangyongyi.carhome.fragment.recommend.news;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.zhangyongyi.carhome.R;
import com.zhangyongyi.carhome.activity.WebViewActivity;
import com.zhangyongyi.carhome.adapter.recommend.news.NewsRecyclerViewAdapter;
import com.zhangyongyi.carhome.db.DaoHelper;
import com.zhangyongyi.carhome.entity.greendao.NewesListEntity;
import com.zhangyongyi.carhome.entity.recommend.NewestEntity;
import com.zhangyongyi.carhome.entity.recommend.ResultEntity;
import com.zhangyongyi.carhome.tools.DividerItemDecoration;
import com.zhangyongyi.carhome.tools.MyOnClickListener;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by dllo on 16/1/8.
 * 新闻
 */
public class NewsFragment extends Fragment implements MyOnClickListener {
    private RecyclerView recyclerView;
    private NewsRecyclerViewAdapter newsRecyclerViewAdapter;

    private RequestQueue queue;

    private DaoHelper helper;

    private ProgressDialog dialog;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_recommend_news, null);
        return v;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        dialog = new ProgressDialog(getActivity());
        dialog.setTitle("加载中...");
        dialog.show();


        recyclerView = (RecyclerView) getActivity().findViewById(R.id.rv_news);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 1);
        recyclerView.setLayoutManager(gridLayoutManager);

        newsRecyclerViewAdapter = new NewsRecyclerViewAdapter(getActivity());
        //分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        recyclerView.setAdapter(newsRecyclerViewAdapter);

        newsRecyclerViewAdapter.setMyOnClickListener(this);


        initData();
        helper = DaoHelper.getInstance();
    }


    private void initData() {


        queue = Volley.newRequestQueue(getActivity());
        String url = "http://app.api.autohome.com.cn/autov4.8.5/news/newslist-pm2-c0-nt1-p1-s20-l0.json";
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                dialog.dismiss();

                Gson gson = new Gson();

                NewestEntity ne = gson.fromJson(response, NewestEntity.class);
                if (ne != null) {
                    ResultEntity re = ne.getResult();
                    if (re != null) {
                        List<NewesListEntity> newesListEntities = re.getNewslist();
                        if (newesListEntities != null && newesListEntities.size() > 0) {
                            newsRecyclerViewAdapter.addData(newesListEntities);
                            helper.addNewestList(newesListEntities);
                        }

                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                newsRecyclerViewAdapter.addData(helper.seacherNewestList());
            }
        }) {


            /**防止乱码 **/
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                try {
                    String jsonString = new String(response.data, "UTF-8");
                    return Response.success(jsonString,
                            HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }

        };
        queue.add(request); // 将请求加入到请求队列中
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (queue != null) {
            queue.cancelAll(this);
        }
    }

    @Override
    public void MyOnClickListener(int id) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), WebViewActivity.class);
        intent.putExtra("id", id);
        Log.d("NewestFragment", "id:" + id);
        getActivity().startActivity(intent);


    }


}